package com.uy.system.utils;

import cn.hutool.json.JSONUtil;
import com.uy.system.model.enums.HttpCode;
import com.uy.system.response.ResponseMessageFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;

/**
 * @Author LY
 * @create 2024/4/23 9:46
 * @Description 响应工具类
 */
public class ResponseUtils {

    /**
     * 异常消息返回(适用过滤器中处理异常响应)
     * @param response
     * @param httpCode
     */
    public static void writeErrMsg(HttpServletResponse response, HttpCode httpCode) throws IOException {
        switch (httpCode) {
            case INVALID_TOKEN:
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                break;
            case PARAMS_ERROR:
                response.setStatus(HttpStatus.PAYMENT_REQUIRED.value());
                break;
            default:
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                break;
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(JSONUtil.toJsonStr(ResponseMessageFactory.getErrorResponseMessage(httpCode)));
    }
}
